<template>
  <div>
    <el-table :data="rows" @cell-dblclick="setValue" :border="true">
      <el-table-column
        v-for="(row, index) in structure"
        :key="index"
        :label="row.title"
        :prop="row.key">
      </el-table-column>
    </el-table>
  </div>
</template>

<script>
export default {
  name: 'index',
  data () {
    return {
      cell: null, // 当前单元格DOM对象
      inputDOM: null,
      activeRow: null,
      activeCol: null,
      readonly: []
    }
  },
  methods: {
    setValue (row, column, cell) {
      if (this.inputDOM) {
        return
      }
      if (this.readonly.indexOf(column.property) !== -1) {
        return
      }
      this.cell = cell
      this.activeRow = row
      this.activeCol = column.property
      let inputDOM = document.createElement('input')
      inputDOM.className = 'table-input'
      inputDOM.onblur = this.cellInputBlur
      inputDOM.onkeypress = this.cellInputEnter
      inputDOM.value = row[column.property]
      cell.appendChild(inputDOM)
      this.inputDOM = inputDOM
      inputDOM.focus()
    },
    cellInputBlur () {
      let value = this.inputDOM.value
      this.inputDOM.onblur = null
      this.cell.removeChild(this.inputDOM)
      this.$set(this.activeRow, this.activeCol, value)
      this.inputDOM = null
      this.$emit('setValue', {value, row: this.activeRow})
    },
    cellInputEnter (e) {
      if (e.keyCode === 13) {
        this.cellInputBlur()
      }
    }
  },
  props: {
    rows: Array,
    structure: {
      type: Array,
      required: true
    }
  },
  created () {
    this.structure.forEach(item => {
      if (item.readonly) {
        this.readonly.push(item.key)
      }
    })
  }
}
</script>

<style scoped>
</style>
